package com.boe.csb.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import com.boe.csb.core.entity.UserInfo;
import com.boe.csb.web.model.ResultModel;

/**
 * Created by tianxiang.luo on 16/12/3.
 */
public class BaseController {

    @Autowired
    private ReloadableResourceBundleMessageSource messageSource;

    public static final String VERIFY_CODE_KEY = "verify_code";

    public static final String LOGIN_FLAG = "login";

    public static final String USER_KEY = "user_info";

    public String fetchUserId(HttpSession session){
        UserInfo userInfo = (UserInfo) session.getAttribute(USER_KEY);
        if(userInfo!=null)
            return String.valueOf(userInfo.getUserId());
        return  null;
    }

    public UserInfo fetchUserInfo(HttpSession session){
        UserInfo userInfo = (UserInfo) session.getAttribute(USER_KEY);
        if(userInfo!=null)
            return userInfo;
        return  null;
    }

    /**
     * 把错误封装成map
     */
    protected ResultModel returnFieldErrorResult(ResultModel resultModel,BindingResult result) {
        Map<String, String> fieldErrorMap = new HashMap<String, String>();
        List<FieldError> fieldErrors = result.getFieldErrors();
        for (FieldError error : fieldErrors) {
            fieldErrorMap.put(error.getField(),
                    messageSource.getMessage(error.getDefaultMessage(), null, Locale.getDefault()));
        }
        resultModel.setFieldErrMsg(fieldErrorMap);
        return resultModel;
    }


}
